import { Component, OnInit, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import {
  SFComponent,
  SFCustomWidgetSchema,
  SFDateWidgetSchema,
  SFNumberWidgetSchema,
  SFRadioWidgetSchema,
  SFSchema,
  SFSelectWidgetSchema,
  SFTextareaWidgetSchema,
  SFUISchema,
  SFUploadWidgetSchema
} from '@delon/form';
import { apiConf } from '@conf/api.conf';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { Observable, Observer } from 'rxjs';
import { EAEnvironmentService } from '@shared';
import { OrderManagementService } from '../../../services/order-management.service';
import format from 'date-fns/format';

@Component({
  selector: 'app-order-management-voucher-view',
  templateUrl: './voucher-view.component.html',
  styleUrls: ['./voucher-view.component.less'],
  providers: [DatePipe]
})
export class orderManagementVoucherViewComponent implements OnInit {
  i: any;
  loadPDF: string = '';
  loadingPlaceDetailedAddress: string = '';
  dischargePlaceDetailedAddress: string = '';
  formData: any;
  datas: any;
  Status: any;
  data: any = {
    weight: 0,
    volume: 0
  };
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema: SFSchema = {};
  ui: SFUISchema = {};
  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    public service: OrderManagementService,
    private datePipe: DatePipe,
    private envSrv: EAEnvironmentService,
    private modalService: NzModalService
  ) {}

  ngOnInit(): void {
    console.log(this.i);
    this.initSF();
    if (this.i) {
      // 获取订单上传详细地址
      this.service.request('/api/sdc/billDriver/getLoadingByBillId', { id: this.i.id }).subscribe(res => {
        console.log(res);
        this.loadingPlaceDetailedAddress = res.loadingPlaceDetailedAddress;
        this.dischargePlaceDetailedAddress = res.dischargePlaceDetailedAddress;
        this.initSF();
      });
    }

    this.initData();
    this.i.time = this.i.loadingTime;
  }
  initSF() {
    console.log(this.Status);
    if (this.Status == 1) {
      this.schema = {
        properties: {
          loadingLadingBillFilePath: {
            type: 'string',
            title: '装货凭证',
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '提货单',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.loadingPlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },
          loadingPeopleVehiclesGoodsFilePath: {
            type: 'string',
            title: '',
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '人车货照片',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.loadingPlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },
          no4: {
            type: 'string',
            title: '',
            ui: {
              widget: 'text'
            },
            default: '单张大小不超过5M，支持.jpg、.jpeg和 .png格式'
          },
          unloadingLadingBillFilePath: {
            type: 'string',
            title: '卸货凭证',
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '提货单',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.dischargePlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },
          unloadingPeopleVehiclesGoodsFilePath: {
            type: 'string',
            title: '',
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '人车货照片',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.dischargePlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          }
        },
        required: [
          'loadingLadingBillFilePath',
          'loadingPeopleVehiclesGoodsFilePath',
          'unloadingLadingBillFilePath',
          'unloadingPeopleVehiclesGoodsFilePath'
        ]
      };
    } else {
      this.schema = {
        properties: {
          no0: {
            type: 'string',
            title: '',
            ui: {
              widget: 'custom'
            }
          },
          loadingLadingBillFilePath: {
            type: 'string',
            title: '装货凭证',
            readOnly: true,
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '提货单',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.loadingPlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },
          loadingPeopleVehiclesGoodsFilePath: {
            type: 'string',
            title: '',
            readOnly: true,
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '人车货照片',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.loadingPlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },

          no4: {
            type: 'string',
            title: '',
            ui: {
              widget: 'text'
            },
            default: '单张大小不超过5M，支持.jpg、.jpeg和 .png格式'
          },
          no6: {
            type: 'string',
            title: '',
            ui: {
              widget: 'custom'
            }
          },
          unloadingLadingBillFilePath: {
            type: 'string',
            title: '卸货凭证',
            readOnly: true,
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '提货单',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.dischargePlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          },
          unloadingPeopleVehiclesGoodsFilePath: {
            type: 'string',
            title: '',
            readOnly: true,
            ui: {
              widget: 'upload',
              action: apiConf.waterFileUpload,
              fileType: 'image/png,image/jpeg,image/jpg,image/gif',
              limit: 1,
              limitFileCount: 1,
              resReName: 'data.fullFileWatermarkPath',
              urlReName: 'data.fullFileWatermarkPath',
              descriptionI18n: '人车货照片',
              data: {
                appId: this.envSrv.env.appId,
                content: [
                  `上传用户:${this.i?.driverName}(${this.i?.driverPhone})`,
                  `上传位置:${this.dischargePlaceDetailedAddress}`,
                  `上传时间:${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}`
                ],
                position: '2',
                fontSize: '100'
              },
              name: 'multipartFile',
              beforeUpload: (file: any, fileList: any) => {
                return new Observable((observer: Observer<boolean>) => {
                  const isLt1M = file.size / 1024 / 1024 < 5;
                  const fileType = 'image/png,image/jpeg';
                  if (fileType.indexOf(file.type) === -1) {
                    this.service.msgSrv.warning('图片格式不正确！');
                    observer.complete();
                    return;
                  }
                  if (!isLt1M) {
                    this.service.msgSrv.warning('图片大小超过5M!');
                    observer.complete();
                    return;
                  }
                  observer.next(isLt1M);
                  observer.complete();
                });
              },
              multiple: false,
              listType: 'picture-card'
            } as SFUploadWidgetSchema
          }
        },
        required: [
          'loadingLadingBillFilePath',
          'loadingPeopleVehiclesGoodsFilePath',
          'unloadingLadingBillFilePath',
          'unloadingPeopleVehiclesGoodsFilePath'
        ]
      };
    }
    this.ui = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 20 }
      },
      $unloadingLadingBillFilePath: { grid: { span: 12 } },
      $unloadingPeopleVehiclesGoodsFilePath: { grid: { span: 12 } },
      $loadingLadingBillFilePath: { grid: { span: 12 } },
      $loadingPeopleVehiclesGoodsFilePath: { grid: { span: 12 } }
    };
  }
  save(value: any): void {
    
    console.log(value);
    const params = {
      id: this.i?.id,
      loadingLadingBillFilePath: value?.loadingLadingBillFilePath?.url || value?.loadingLadingBillFilePath,
      loadingPeopleVehiclesGoodsFilePath: value?.loadingPeopleVehiclesGoodsFilePath?.url || value?.loadingPeopleVehiclesGoodsFilePath,
      unloadingLadingBillFilePath:
        value?.unloadingLadingBillFilePath?.url || value?.unloadingLadingBillFilePath ,
      unloadingPeopleVehiclesGoodsFilePath:
        value?.unloadingPeopleVehiclesGoodsFilePath?.url || value?.unloadingPeopleVehiclesGoodsFilePath
    };
    if(!value.loadingLadingBillFilePath) {
       params.loadingLadingBillFilePath =''
    }
    if(!value.loadingPeopleVehiclesGoodsFilePath) {
       params.loadingPeopleVehiclesGoodsFilePath =''
    }
    if(!value.unloadingLadingBillFilePath) {
       params.unloadingLadingBillFilePath =''
    }
    if(!value.unloadingPeopleVehiclesGoodsFilePath) {
       params.unloadingPeopleVehiclesGoodsFilePath =''
    }
    console.log(params.loadingLadingBillFilePath == '');
    console.log(params.loadingPeopleVehiclesGoodsFilePath =='');
    console.log(params.loadingLadingBillFilePath !=='' || params.loadingPeopleVehiclesGoodsFilePath !=='');
    console.log((params.unloadingLadingBillFilePath !=='' || params.unloadingPeopleVehiclesGoodsFilePath !==''));
    console.log(false && true);
    
    if (!((params.loadingLadingBillFilePath !=='' || params.loadingPeopleVehiclesGoodsFilePath !=='') && (params.unloadingLadingBillFilePath !=='' || params.unloadingPeopleVehiclesGoodsFilePath !=='')) ) {
      this.service.msgSrv.warning('装货凭证和装货凭证必须上传一种！');
      return;
    }
    console.log(params);
    this.service.request(this.service.$api_get_updateBillExamine, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改成功！');
        this.modal.destroy(true);
      }
    });
  }
  sure() {
    // const params = [this.i?.id];
    // this.service.downloadFile(this.service.$api_createBillTakeGoods, params);
    // this.service.downloadFile(this.service.$api_createBillDischargeGoods, params);
    // 逻辑： 先判断电子提货单是否已生成，文件为空则触发签署文件，再查询是否签署成功，成功则退出，刷新页面，再次点击为预览
    let time = 10;
    setInterval(function () {
      time -= 1;
    }, 1000);
    const modal = this.modalService.success({
      nzTitle: '电子装货单和电子卸货单签署中！',
      nzContent: `
        请等待${time}秒后自动关闭
        `
    });
    this.service.request(this.service.$api_createBillEsignGoods, [this.datas?.id]).subscribe(res => {
      if (res) {
        res.forEach((element: any) => {
          switch (element?.esignFlowStatus) {
            case '1':
              setTimeout(() => {
                this.service.request(this.service.$api_getBillGoodsEsignFile, [this.datas?.id]).subscribe(res => {
                  if (res[0]?.esignFlowStatus == '2') {
                    this.service.msgSrv.success('生成电子单据成功！');
                    this.modal.destroy(true);
                  }
                });
              }, 9000);
              return;
            default:
              this.service.msgSrv.error('签署异常!');
              modal.destroy();
              return;
          }
        });
      } else {
        this.service.msgSrv.error('签署异常!');
        modal.destroy();
      }
    });
  }
  //  确认到车界面信息(两个只能看的图片)
  initData() {
    this.service.request(this.service.$api_get_getCredentials, { id: this.i?.id }).subscribe(res => {
      console.log(res);
      this.datas = res;
      if (res.unloadingLadingBillFilePath) {
        this.formData = {
          loadingLadingBillFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res.loadingLadingBillFilePath,
              response: {
                url: res.loadingLadingBillFilePath
              }
            }
          ],
          loadingPeopleVehiclesGoodsFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res.loadingPeopleVehiclesGoodsFilePath,
              response: {
                url: res.loadingPeopleVehiclesGoodsFilePath
              }
            }
          ],
          unloadingLadingBillFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res.unloadingLadingBillFilePath,
              response: {
                url: res.unloadingLadingBillFilePath
              }
            }
          ],
          unloadingPeopleVehiclesGoodsFilePath: [
            {
              uid: 'logo',
              name: 'LOGO',
              status: 'done',
              url: res.unloadingPeopleVehiclesGoodsFilePath,
              response: {
                url: res.unloadingPeopleVehiclesGoodsFilePath
              }
            }
          ]
        };
      }
    });
  }
  close(): void {
    this.modal.destroy(true);
  }
  openlaod(value: any) {
    if (value === 1) {
      this.service.request(this.service.$api_getBillTakeGoods, { id: this.datas?.id }).subscribe(res => {
        if (res) {
          console.log(res);
          window.open(res?.contractFilePath);
        }
      });
    } else {
      this.service.request(this.service.$api_getBillDischargeGoods, { id: this.datas?.id }).subscribe(res => {
        if (res) {
          console.log(res);
          window.open(res?.contractFilePath);
        }
      });
    }
  }
}
